﻿using System.Web.Security;
using System.Web.Mvc;
using tcms.Models;
using System.Linq;
using System;

namespace tcms.Controllers
{
	[Authorize]
	public class AccountController : Controller
	{
		//
		// GET: /Account/Login

		[AllowAnonymous]
		public ActionResult Login(string returnUrl)
		{
			ViewBag.ReturnUrl = returnUrl;
			return View();
		}

		//
		// POST: /Account/Login

		[HttpPost]
		[AllowAnonymous]
		[ValidateAntiForgeryToken]
		public ActionResult Login(LoginModel model, string returnUrl)
		{
			if (ModelState.IsValid)
			{
				if (Membership.ValidateUser(model.UserName, model.Password))
				{
					FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
					if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
						&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
					{
						return Redirect(returnUrl);
					}
					else
					{
                        //string[] ary = Roles.GetAllRoles();
                        //if (Roles.IsUserInRole(model.UserName, "admin"))
                        return RedirectToAction("Index", "Home");
                        //else if (Roles.IsUserInRole(model.UserName, "staff"))
                        //    return RedirectToAction("Index", "Staff", new { planner = model.UserName });
                        //else if (Roles.IsUserInRole(model.UserName, "manager"))
                        //    return RedirectToAction("Index", "Manager");
					}
				}
				else
				{
					ModelState.AddModelError("", "用户名或密码错误");
				}
			}

			// If we got this far, something failed, redisplay form
			return View(model);
		}

        [HttpGet]
        public ActionResult Update()
        {
            return View();
        }

        [HttpPost]
        public string Update(string oldPassword, string password)
        {
            try
            {
                MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                if (currentUser.ChangePassword(oldPassword, password))
                {
                    return "success";
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                return ex.Message;
            }

            Response.StatusCode = 500;
            return "Fail to change password";
        }

		[HttpGet]
		public JsonResult UserExist(string UserName)
		{
			if (Membership.GetUser(UserName) != null)
			{
				return Json(false, JsonRequestBehavior.AllowGet);
			}

			return Json(true, JsonRequestBehavior.AllowGet);
		}

		//
		// POST: /Account/LogOff

		//[HttpPost]
		//[ValidateAntiForgeryToken]
		public ActionResult LogOff()
		{
			FormsAuthentication.SignOut();

			return RedirectToAction("Login", "Account");
		}

		//
		// GET: /Account/Register

		[AllowAnonymous]
		public ActionResult Register()
		{
			return View();
		}

		//
		// POST: /Account/Register

		[HttpPost]
		[Authorize(Roles="admin")]
		[ValidateAntiForgeryToken]
		public string Register(RegisterModel model)
		{
			if (ModelState.IsValid)
			{
				// Attempt to register the user
				MembershipCreateStatus createStatus;
				Membership.CreateUser(model.UserName, model.Password, null, null, null, true, null, out createStatus);

				if (createStatus == MembershipCreateStatus.Success)
				{
					Roles.AddUserToRole(model.UserName, model.Role);

					return "添加成功";
				}
			    Response.StatusCode = 500;
                return ErrorCodeToString(createStatus);
			}

            return "invalid";
		}

        [HttpGet]
        [Authorize(Roles = "admin")]
        public ActionResult Users()
        {
            var users = Membership.GetAllUsers().OfType<MembershipUser>().Select(mu => new UserModel(mu));
            return View(users);
        }

        public string Delete(int id)
        {
            try
            {
                var user = Membership.GetUser(id);
                Membership.DeleteUser(user.UserName);
                return "删除成功";
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                return "删除用户失败";
            }
        }

		#region Helpers
		private ActionResult RedirectToLocal(string returnUrl)
		{
			if (Url.IsLocalUrl(returnUrl))
			{
				return Redirect(returnUrl);
			}
			else
			{
				return RedirectToAction("Index", "Home");
			}
		}

		public enum ManageMessageId
		{
			ChangePasswordSuccess,
			SetPasswordSuccess,
			RemoveLoginSuccess,
		}

		private static string ErrorCodeToString(MembershipCreateStatus createStatus)
		{
			// See http://go.microsoft.com/fwlink/?LinkID=177550 for
			// a full list of status codes.
			switch (createStatus)
			{
				case MembershipCreateStatus.DuplicateUserName:
					return "User name already exists. Please enter a different user name.";

				case MembershipCreateStatus.DuplicateEmail:
					return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

				case MembershipCreateStatus.InvalidPassword:
					return "The password provided is invalid. Please enter a valid password value.";

				case MembershipCreateStatus.InvalidEmail:
					return "The e-mail address provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidAnswer:
					return "The password retrieval answer provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidQuestion:
					return "The password retrieval question provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidUserName:
					return "The user name provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.ProviderError:
					return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

				case MembershipCreateStatus.UserRejected:
					return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

				default:
					return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
			}
		}
		#endregion
	}
}
